package com.jihox.abookpro;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import android.app.Dialog;
import android.app.FragmentManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.res.Resources;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import android.provider.MediaStore;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jihox.abookpro.R;
import com.jihox.abookpro.adapter.DragAdapter;
import com.jihox.abookpro.adapter.PhotoChildAdapter;
import com.jihox.abookpro.adapter.PhotoChildAdapter.ConvertViewOnClickListener;
import com.jihox.abookpro.domain.BookProduct;
import com.jihox.abookpro.fragment.AssertFragment;
import com.jihox.abookpro.util.AndroidImageFile;
import com.jihox.abookpro.util.DensityUtil;
import com.jihox.abookpro.util.NativeImageLoader;
import com.jihox.abookpro.util.PictureUtil;
import com.jihox.abookpro.view.DragGridView;
import com.jihox.abookpro.view.GalleryHorizontalView;
import com.jihox.abookpro.view.ShowPhotoImageView;
import com.jihox.abookpro.view.ViewHolder;
import com.jihox.abookpro.view.DragGridView.OnReorderItemsListener;
import com.jihox.abookpro.R.drawable;
import com.nineoldandroids.animation.Animator;
import com.nineoldandroids.animation.Animator.AnimatorListener;
import com.nineoldandroids.animation.AnimatorSet;
import com.nineoldandroids.animation.ObjectAnimator;

public class ShowImageActivity extends BaseActivity {
	private GridView mGridView;
	private PhotoChildAdapter photoChildAdapter;
	private RelativeLayout relativeLayoutOfSelectedPhotoList;
	public static ArrayList<AndroidImageFile> selectedPhotoList = new ArrayList<AndroidImageFile>();
	public static boolean showNextButton = false;
	private Vibrator mVibrator;
	public static int currentScrollX = 0;
	public static int selected_photo_height = 180;
	public static int selected_photo_width = 200;
	private DragGridView mDragGridView ;
	private GalleryHorizontalView galleryHorizontalView;
	private Handler mHandler = new Handler();
	private Button nextStep;
	private float selectedPhotoListTitleHeight;
	private DragAdapter mDragAdapter;
	private String folderName;
	private String childListName;
	private BookProduct bookProduct;
	private AssertFragment assertFragment;
	private FragmentManager manager;
	private boolean isShowImageNeedAssert;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		//requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);

		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
		setContentView(R.layout.activity_show_image);
		SharedPreferences preferences = getSharedPreferences(
				"assert_pref", Context.MODE_APPEND);
		isShowImageNeedAssert = preferences.getBoolean("isShowImageNeedAssert", true);
		manager=getFragmentManager();
		bookProduct = MyApplication.getInstance().getBookProduct();
		
		Button returnButton = (Button)findViewById(R.id.btnReturn); 
		returnButton.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View arg0) {
				goToGallerySelectActivity();
			}

		});
		nextStep = (Button) findViewById(R.id.shimg_btnnext);  
		nextStep.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View arg0) {
				
				Intent intent = new Intent();
				intent.setClass(ShowImageActivity.this, CurlActivity.class);  
				NativeImageLoader.getInstance().clearCacheButTheSelectedPhotoList(ShowImageActivity.selectedPhotoList);
				setResult(RESULT_OK,intent);
				finish();
			}
		});

		mVibrator = (Vibrator) this.getSystemService(Context.VIBRATOR_SERVICE);
		//		Resources resources = getResources();
		//		selected_photo_height = resources.getInteger(R.integer.selected_photo_height);
		//		selected_photo_height = DensityUtil.dip2px(this, selected_photo_height);
		//		selected_photo_width = resources.getInteger(R.integer.selected_photo_width);
		//		selected_photo_width = DensityUtil.dip2px(this, selected_photo_width);
		//		selectedPhotoListTitleHeight = resources.getDimension(R.dimen.selectedPhotoListTitleHeight);

		relativeLayoutOfSelectedPhotoList = (RelativeLayout) findViewById(R.id.selectedPhotoList);
		TextView showImageTitleTextView = (TextView) findViewById(R.id.show_image_title);
		folderName = getIntent().getStringExtra("folderName");
		showImageTitleTextView.setText(folderName);
		galleryHorizontalView = (GalleryHorizontalView) findViewById(R.id.galleryHorizontalView);
		
		//		mDragGridView = (DragGridView) findViewById(R.id.dragGridView);

		//		//		addItemToSelectedPhotoList("sdf");
		//		LayoutParams params = new LayoutParams(
		//				selectedPhotoList.size() *selected_photo_width, selected_photo_height);
		//		//				folderPhotoList.size() *320,270 );
		//		mDragGridView.setLayoutParams(params);
		//		mDragGridView.setColumnWidth(selected_photo_width);
		//		//		mDragGridView.setColumnWidth(350);
		//		mDragGridView.setHorizontalSpacing(0);
		//		mDragGridView.setGravity(Gravity.CENTER);
		//		mDragGridView.setStretchMode(GridView.NO_STRETCH);
		//		mDragGridView.setNumColumns(selectedPhotoList.size());

		//		mDragAdapter = new DragAdapter(this, selectedPhotoList,mDragGridView);

		//		mDragGridView.setAdapter(mDragAdapter);
		//		mDragGridView.setOnDetailItemDeleteListener(new OnDetailItemDeleteListener() {
		//			@Override
		//			public void onDelete(AndroidImageFile aif) {
		//				//galleryHorizontalView.smoothScrollTo((int) convertView.getX(), 0);
		//				for(int indexx = 0;indexx <selectedPhotoList.size();indexx++){
		//					if(selectedPhotoList.get(indexx).equals(aif)){
		//						selectedPhotoList.remove(indexx);
		//						for(int index = 0;index<photoChildAdapter.getAlbumPhotoList().size();index++){
		//							if(photoChildAdapter.getAlbumPhotoList().get(index).equals(aif)){
		//								photoChildAdapter.getmSelectMap().put(index, false);//删除去掉的照片的勾选状态
		//								break;
		//							}
		//						}
		//						break;
		//					}
		//				}
		//				LayoutParams params = new LayoutParams(
		//						selectedPhotoList.size() *selected_photo_width, selected_photo_height);
		//				mDragGridView.setLayoutParams(params);
		//				mDragGridView.setNumColumns(selectedPhotoList.size());
		//				updateSelectedPhotoList();
		//				photoChildAdapter.userNotifyDataSetChanged();
		//				mDragAdapter.notifyDataSetChanged();
		//				invalidateNextStep();
		//			}
		//		});
		//		mDragGridView.setOnReorderItemsListener(new OnReorderItemsListener() {
		//
		//			@Override
		//			public void reorderItems(int from, int to) {
		//				AndroidImageFile temp = selectedPhotoList.get(from);
		//				//这里的处理需要注意下
		//				if(from < to){
		//					for(int i=from; i<to; i++){
		//						Collections.swap(selectedPhotoList, i, i+1);
		//					}
		//				}else if(from > to){
		//					for(int i=from; i>to; i--){
		//						Collections.swap(selectedPhotoList, i, i-1);
		//					}
		//				}
		//				selectedPhotoList.set(to, temp);
		//				//设置新到的item隐藏，不用调用notifyDataSetChanged来刷新界面，因为setItemHide方法里面调用了
		//				mDragAdapter.setHideItem(-1);
		//				photoChildAdapter.userNotifyDataSetChanged();//selectedPhotoList
		//			}
		//		});

		if(showNextButton){    
			nextStep.setVisibility(View.VISIBLE);
		}else{
			nextStep.setVisibility(View.INVISIBLE);
		}

		mGridView = (GridView) findViewById(R.id.child_grid);
		childListName = getIntent().getStringExtra("childListName");
		photoChildAdapter = new PhotoChildAdapter(getApplicationContext(), mGroupMap.get(childListName), selectedPhotoList, mGridView);
		photoChildAdapter.setConvertViewOnClickListener(new ConvertViewOnClickListener() {
			//存在一个bug，Gridview第一个没有动画！！
			@Override
			public void onClick(ViewHolder viewHolder,int position, AndroidImageFile aif) {
				int index = -1;
				if((index = checkImageFileLost(selectedPhotoList)) >= 0){
					if (!viewHolder.mCheckBox.isChecked()) {
						replaceLostFile(index,aif);
					}else{
						doOnGridViewItemClick(viewHolder, position, aif, mDragGridView, mDragAdapter);
					}
				}
				else if(selectedPhotoList.size()<bookProduct.getNumOfPictures() || viewHolder.mCheckBox.isChecked()){
					doOnGridViewItemClick(viewHolder, position, aif, mDragGridView, mDragAdapter);

				}else{
					invalidateNextStep();
					mVibrator.vibrate(100);
					showToast(getResources().getString(R.string.T_Photo_Full));
				}
			}
		});
		mGridView.setAdapter(photoChildAdapter);
		//		mGridView.setOnItemClickListener(new OnItemClickListener() {
		//			public void onItemClick(AdapterView<?> parent, final View convertView,
		//					int position, long id) {
		//				final ViewHolder viewHolder = new ViewHolder();
		//				viewHolder.mImageView = (ShowPhotoImageView) convertView.findViewById(R.id.child_image);
		//				viewHolder.mCheckBox = (CheckBox) convertView.findViewById(R.id.child_checkbox);
		//				viewHolder.mTextView = (TextView) convertView.findViewById(R.id.child_number);
		//				viewHolder.mHintTextView = (TextView) convertView.findViewById(R.id.child_number_hint);
		//				if(selectedPhotoList.size()<GallerySelectActivity.bookProduct.getNumOfPictures()||viewHolder.mCheckBox.isChecked()){
		//					AndroidImageFile aif = (AndroidImageFile) ((ImageView)convertView.findViewById(R.id.child_image)).getTag();
		//					if (!viewHolder.mCheckBox.isChecked()) {
		//						if (!PictureUtil.isSuitablePicture(aif.getPath(),
		//								pixelsOfPicture)) {
		//							showDialog(viewHolder, position, aif, mDragGridView, mDragAdapter);
		//							return;
		//						}
		//					}
		//					doOnGridViewItemClick(viewHolder, position, aif, mDragGridView, mDragAdapter);
		//
		//				}else{
		//					invalidateNextStep();
		//					showToast();
		//				}
		//			}
		//			Toast toast = null;
		//			private synchronized void showToast() {
		//				mVibrator.vibrate(100);
		//				if(toast==null)
		//					toast = Toast.makeText(getApplicationContext(), "相册已满", Toast.LENGTH_SHORT);
		//				toast.show();
		//			}
		//		});
		updateSelectedPhotoList();
		mHandler.postDelayed(new Runnable() {
			@Override
			public void run() {
				galleryHorizontalView.scrollTo(currentScrollX, 0);
			}
		},10);

		this.getContentResolver().registerContentObserver( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, true, new ImagesObserver(new Handler()){
			@Override
			public void onChange(boolean selfChange) {
				getImages();

				updateSelectedPhotoList();
			}
		});
		TextView selectedPhotoListTitleTextView = (TextView) findViewById(R.id.selectedPhotoListTitle);
		selectedPhotoListTitleTextView.setText(
//				getResources().getString(R.string.T_Selected_text)
				getResources().getString(R.string.T_Split_text)
				+bookProduct.getNumOfPictures()
//				+selectedPhotoList.size()
				+getResources().getString(R.string.T_Page_text));
		invalidateNextStep();
		if(ShowImageActivity.selectedPhotoList.size() == bookProduct.getMaxPictures()){
			showNextButton = true;
			nextStep.setEnabled(true);
			nextStep.setVisibility(View.VISIBLE);
		}
	}

	private int checkImageFileLost(List<AndroidImageFile> selectedFileList){
		int index = -1;
		if(selectedFileList != null){
			for(int i =0; i < selectedFileList.size(); i++)
			{
				File file = new File(selectedFileList.get(i).getPath());
				if(!file.exists())
				{
					index = i;
					break;
				}
			}
		}
		return index;
	}
	
	private void replaceLostFile(int index, AndroidImageFile aif){
		selectedPhotoList.get(index).setPath(aif.getPath());
		selectedPhotoList.get(index).setFolderName(aif.getFolderName());
		updateSelectedPhotoList();
		mDragAdapter.notifyDataSetChanged();
		
		if (checkImageFileLost(selectedPhotoList)>= 0){
			return;
		}

		invalidateNextStep();
		if(ShowImageActivity.selectedPhotoList!=null
				&& ShowImageActivity.selectedPhotoList.size()==bookProduct.getNumOfPictures()
				&& !showNextButton){    
			showNextButton =true;
			nextStep.setVisibility(View.VISIBLE);

			Animation shake = AnimationUtils.loadAnimation(ShowImageActivity.this, R.anim.button_anim);
			nextStep.startAnimation(shake);
		}
	}
	protected void scanOKHandle(){
		photoChildAdapter = new PhotoChildAdapter(getApplicationContext(), mGroupMap.get(childListName), selectedPhotoList, mGridView);
		mGridView.setAdapter(photoChildAdapter);
		photoChildAdapter.setConvertViewOnClickListener(new ConvertViewOnClickListener() {
			//存在一个bug，Gridview第一个没有动画！！
			@Override
			public void onClick(ViewHolder viewHolder,int position, AndroidImageFile aif) {
				
				int index = -1;
				if((index = checkImageFileLost(selectedPhotoList)) >= 0){
					replaceLostFile(index, aif);
				}
				else if(selectedPhotoList.size()<bookProduct.getNumOfPictures()||viewHolder.mCheckBox.isChecked()){
					doOnGridViewItemClick(viewHolder, position, aif, mDragGridView, mDragAdapter);

				}else{
					invalidateNextStep();
					mVibrator.vibrate(100);
					showToast(getResources().getString(R.string.T_Photo_Full));
				}
			}
		});
		firstScanFlag = false;
	}

	@Override
	protected void onResume() {

		Resources resources = getResources();
		selected_photo_height = resources.getInteger(R.integer.selected_photo_height);
		selected_photo_height = DensityUtil.dip2px(this, selected_photo_height);
		selected_photo_width = resources.getInteger(R.integer.selected_photo_width);
		selected_photo_width = DensityUtil.dip2px(this, selected_photo_width);
		selectedPhotoListTitleHeight = resources.getDimension(R.dimen.selectedPhotoListTitleHeight);
		mDragGridView = (DragGridView) findViewById(R.id.dragGridView);

		//		addItemToSelectedPhotoList("sdf");
		LayoutParams params = new LayoutParams(
				ShowImageActivity.selectedPhotoList.size() *selected_photo_width, selected_photo_height);
		//				folderPhotoList.size() *320,270 );
		mDragGridView.setLayoutParams(params);
		mDragGridView.setColumnWidth(selected_photo_width);
		//		mDragGridView.setColumnWidth(350);
		mDragGridView.setHorizontalSpacing(0);
		mDragGridView.setGravity(Gravity.CENTER);
		mDragGridView.setStretchMode(GridView.NO_STRETCH);
		mDragGridView.setNumColumns(ShowImageActivity.selectedPhotoList.size());

		mDragAdapter = new DragAdapter(this, ShowImageActivity.selectedPhotoList,mDragGridView);

		mDragGridView.setAdapter(mDragAdapter);
		//		mDragGridView.setOnDetailItemDeleteListener(new OnDetailItemDeleteListener() {
		//			@Override
		//			public void onDelete(AndroidImageFile aif) {
		//				//				galleryHorizontalView.smoothScrollTo((int) convertView.getX(), 0);
		//				for(int indexx = 0;indexx <ShowImageActivity.selectedPhotoList.size();indexx++){
		//					if(ShowImageActivity.selectedPhotoList.get(indexx).equals(aif)){
		//						ShowImageActivity.selectedPhotoList.remove(indexx);
		//						break;
		//					}
		//				}
		//				LayoutParams params = new LayoutParams(
		//						ShowImageActivity.selectedPhotoList.size() *selected_photo_width, selected_photo_height);
		//				mDragGridView.setLayoutParams(params);
		//				mDragGridView.setNumColumns(ShowImageActivity.selectedPhotoList.size());
		//
		//				updateSelectedPhotoList();
		//				mDragAdapter.notifyDataSetChanged();
		//				invalidateNextStep();
		//			}
		//		});

		mDragGridView.setOnReorderItemsListener(new OnReorderItemsListener() {

			@Override
			public void reorderItems(int from, int to) {
				AndroidImageFile temp = ShowImageActivity.selectedPhotoList.get(from);
				//这里的处理需要注意下
				if(from < to){
					for(int i=from; i<to; i++){
						Collections.swap(ShowImageActivity.selectedPhotoList, i, i+1);
					}
				}else if(from > to){
					for(int i=from; i>to; i--){
						Collections.swap(ShowImageActivity.selectedPhotoList, i, i-1);
					}
				}
				ShowImageActivity.selectedPhotoList.set(to, temp);
				//设置新到的item隐藏，不用调用notifyDataSetChanged来刷新界面，因为setItemHide方法里面调用了
				mDragAdapter.setHideItem(-1);
				photoChildAdapter.userNotifyDataSetChanged();
			}
		});

		mHandler.postDelayed(new Runnable() {
			@Override
			public void run() {
				galleryHorizontalView.scrollTo(ShowImageActivity.currentScrollX, 0);
			}
		},10);
		updateSelectedPhotoList();
		super.onResume();
	};

	@Override
	protected void onPause() {
		super.onPause();
	}
	
	@Override
	protected void onDestroy() {
		int count = mGridView.getCount();
		for (int i = 0; i < count; i++) {
			FrameLayout fl = (FrameLayout) mGridView.getChildAt(i);
			if (fl != null) {
				ShowPhotoImageView mImageView = (ShowPhotoImageView) fl
						.findViewById(R.id.child_image);

				if (mImageView != null) {
					BitmapDrawable bd = (BitmapDrawable)mImageView.getDrawable();
					mImageView.setImageResource(0);
					bd.setCallback(null);
					//bd.getBitmap().recycle();
				}
			}
		}
		
		count = mDragGridView.getCount();
		for (int i = 0; i < count; i++) {
			RelativeLayout rl = (RelativeLayout) mDragGridView.getChildAt(i);
			if (rl != null) {
				ImageView mImageView = (ImageView) rl
						.findViewById(R.id.item_image);

				if (mImageView != null) {
					BitmapDrawable bd = (BitmapDrawable)mImageView.getDrawable();
					mImageView.setImageResource(0);
					bd.setCallback(null);
					//bd.getBitmap().recycle();
				}
			}
		}
		System.gc();
		super.onDestroy();
	}
	
	private void invalidateNextStep() {
		// TODO Auto-generated method stub
		if(ShowImageActivity.showNextButton){  
			nextStep.setVisibility(View.VISIBLE); 
			if (ShowImageActivity.selectedPhotoList!=null&&ShowImageActivity.selectedPhotoList.size()==bookProduct.getNumOfPictures()){
				nextStep.setEnabled(true);  
				nextStep.setBackgroundResource(drawable.button_blue_style);
			} else{  
				nextStep.setEnabled(false);  
				nextStep.setBackgroundResource(drawable.greypressed);
			}
		}	else{  
			nextStep.setVisibility(View.INVISIBLE); 
		}
	}
	/**
	 * 给CheckBox加点击动画，利用开源库nineoldandroids设置动画 
	 */
	private void addAnimationForCheckBox(View checkBox){
		float [] values1 = new float[]{0.5f, 0.6f, 0.7f, 0.8f, 0.9f, 1.0f, 1.1f, 1.2f, 1.3f, 1.25f, 1.2f, 1.15f, 1.1f, 1.0f};
		AnimatorSet set = new AnimatorSet();
		set.playTogether(ObjectAnimator.ofFloat(checkBox, "scaleX", values1), 
				ObjectAnimator.ofFloat(checkBox, "scaleY", values1));
		set.setDuration(150);
		set.start();
	}

	private void addAnimationForHintTextView(final TextView hintTextView){

		//		float targetWidth  = mImageView.getWidth();
		//		float targetHeight = mImageView.getHeight();
		//		float hintTextViewWidth = hintTextView.getWidth();
		//		float hintTextViewHeight = hintTextView.getHeight();
		//		float xRatio = targetWidth / hintTextViewWidth;
		//		float yRatio = targetHeight / hintTextViewHeight;

		float [] values = new float[]{0.7f,0.8f,0.9f,1f,1.1f,1.2f,1.3f,1.4f,1.5f,1.6f,1.7f,1.8f};
		//		float [] values2x = new float[]{1f,1.1f,1.2f,1.4f,1.6f,1.8f,2.0f,2.3f,2.6f,2.9f,0f};
		//		float [] values2y = new float[]{1f,1.1f,1.2f,1.4f,1.6f,1.8f,2.0f,2.3f,2.6f,2.9f,0f};
		//		if(xRatio>1&&yRatio>1){
		//			float stepx = xRatio/9;
		//			float stepy = yRatio/9;
		//			values2x = new float[11];
		//			values2x[0]=1f;
		//			values2x[10]=0f;
		//			values2y[0]=1f;
		//			values2y[10]=0f;
		//			for(int i =1;i<10;i++){
		//				values2x[i]=values2x[0]+stepx*i;
		//				values2y[i]=values2y[0]+stepy*i;
		//			}
		//		}
		//		ObjectAnimator alpha1 = ObjectAnimator.ofFloat(hintTextView, "alpha",0f,1f);
		ObjectAnimator scaleX = ObjectAnimator.ofFloat(hintTextView, "scaleX", values);
		ObjectAnimator scaleY = ObjectAnimator.ofFloat(hintTextView, "scaleY", values);
		ObjectAnimator fadeOut = ObjectAnimator.ofFloat(hintTextView, "alpha",1f,0f);

		//		alpha1.setDuration(0);
		scaleX.setDuration(400);
		scaleY.setDuration(400);
		fadeOut.setDuration(420);
		AnimatorSet set0 = new AnimatorSet();
		//		set0.play(keep).before(scaleX);
		set0.play(scaleX).with(scaleY);
		set0.play(fadeOut).with(scaleY);

		set0.addListener(new AnimatorListener() {
			@Override
			public void onAnimationStart(Animator arg0) {
			}
			@Override
			public void onAnimationRepeat(Animator arg0) {
			}

			@Override
			public void onAnimationEnd(Animator arg0) {
				hintTextView.setText("        ");
				hintTextView.setAlpha(1);
				hintTextView.invalidate();
			}

			@Override
			public void onAnimationCancel(Animator arg0) {
			}
		});
		set0.start();
	}



	public void updateSelectedPhotoList() { //同时更新下方列表的显示情况
		photoChildAdapter.userNotifyDataSetChanged();//顺便刷新gridview
		TextView selectedPhotoListNum = (TextView) findViewById(R.id.selectedPhotoListNum);
		selectedPhotoListNum.setText(getResources().getString(R.string.T_Selected_text)
				+selectedPhotoList.size());
//				+getResources().getString(R.string.T_Page_text));
		RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) mGridView
				.getLayoutParams();
		if(!(selectedPhotoList.size()>0)){
			//			if(!(selectedPhotoList.size()>0)){
			layoutParams.bottomMargin = 0;
			layoutParams.setMargins(0, 0, 0, 0);
			mGridView.setLayoutParams(layoutParams);
			relativeLayoutOfSelectedPhotoList.setVisibility(View.INVISIBLE);
		}else{
			layoutParams.bottomMargin = selected_photo_height;
			layoutParams.setMargins(0, 0, 0,(int) (selected_photo_height+selectedPhotoListTitleHeight)+25);//当selectedlist里面有照片时，显示所有照片的layout需要改变大小来适应
			mGridView.setLayoutParams(layoutParams);
			relativeLayoutOfSelectedPhotoList.setVisibility(View.VISIBLE);
		}
		invalidateNextStep();
	}
	///mnt/sdcard/DCIM/Camera/IMG_20140319_020453.jpg
	@Override
	public void onBackPressed() {
		//		Toast.makeText(this, galleryHorizontalView.getScrollX()+"", Toast.LENGTH_LONG).show();
		goToGallerySelectActivity();
	}
	private void goToGallerySelectActivity() {
		currentScrollX = galleryHorizontalView.getScrollX();
		Intent intent = new Intent();    
		intent.setClass(ShowImageActivity.this, GallerySelectActivity.class);  
		setResult(RESULT_CANCELED,intent);
		finish();
	}

	private void doOnGridViewItemClick(ViewHolder viewHolder, int position, AndroidImageFile aif,
			DragGridView mDragGridView, DragAdapter mDragAdapter) {
//		viewHolder.mCheckBox.setChecked(true));
		viewHolder.mCheckBox.setChecked(!viewHolder.mCheckBox.isChecked());
		Drawable d = viewHolder.mImageView.getDrawable();//This is available from API level 1.setImageDrawable need 16
		d.setAlpha(viewHolder.mCheckBox.isChecked()?100:255);
		viewHolder.mImageView.setImageDrawable(d);


		//		viewHolder.mImageView.setImageAlpha(viewHolder.mCheckBox.isChecked()?100:255);
		//		viewHolder.mImageView.setAlpha(viewHolder.mCheckBox.isChecked()?0.5f:1f);

		if(viewHolder.mCheckBox.isChecked()){
			viewHolder.mHintTextView.setText(selectedPhotoList.size()+1 + " of " + bookProduct.getNumOfPictures());
			addAnimationForHintTextView(viewHolder.mHintTextView);
		}
		addAnimationForCheckBox(viewHolder.mCheckBox);
		if(viewHolder.mCheckBox.isChecked()){
			photoChildAdapter.getmSelectMap().put(position, true);
			selectedPhotoList.add(aif);
			LayoutParams params = new LayoutParams(
					selectedPhotoList.size() *selected_photo_width, selected_photo_height);
			mDragGridView.setLayoutParams(params);
			mDragGridView.setNumColumns(selectedPhotoList.size());
			//设置引导
			if(selectedPhotoList.size()==3){
				if(isShowImageNeedAssert){
					DisplayMetrics metric = new DisplayMetrics();
			        getWindowManager().getDefaultDisplay().getMetrics(metric);
					//获取控件在屏幕中的坐标
					int[] location = new int[2];
					mDragGridView.getLocationOnScreen(location);
					Rect rect=new Rect(location[0], location[1], metric.widthPixels, location[1]+mDragGridView.getMeasuredHeight());
					assertFragment=new AssertFragment(1,rect,selected_photo_height);
					manager.beginTransaction().add(R.id.layout_container, assertFragment).commit();
					isShowImageNeedAssert=false;
				}
			}
			galleryHorizontalView.postDelayed(new Runnable() {//选中照片后，自动滑动到右边
				public void run() {
					galleryHorizontalView.fullScroll(HorizontalScrollView.FOCUS_RIGHT);
				}
			}, 100L);
		}else{
			//						galleryHorizontalView.smoothScrollTo((int) convertView.getX(), 0);
			photoChildAdapter.getmSelectMap().put(position, false);//删除去掉的照片
			for(int index = 0;index <selectedPhotoList.size();index++){
				if(selectedPhotoList.get(index).equals(aif)){
					selectedPhotoList.remove(index);
					break;
				}
			}
			LayoutParams params = new LayoutParams(
					selectedPhotoList.size() *selected_photo_width, selected_photo_height);
			mDragGridView.setLayoutParams(params);
			mDragGridView.setNumColumns(selectedPhotoList.size());
		}
		updateSelectedPhotoList();
		mDragAdapter.notifyDataSetChanged();

		invalidateNextStep();

		if(ShowImageActivity.selectedPhotoList!=null
				&& ShowImageActivity.selectedPhotoList.size()==bookProduct.getNumOfPictures()
				&& !showNextButton){    
			showNextButton =true;
			nextStep.setVisibility(View.VISIBLE);

			Animation shake = AnimationUtils.loadAnimation(this, R.anim.button_anim);
			nextStep.startAnimation(shake);
			/*AlphaAnimation alphaAnim = new AlphaAnimation(0.1f, 1.0f);
			alphaAnim.setDuration(600);
			nextStep.setAnimation(alphaAnim);
			alphaAnim.start();

			alphaAnim.setAnimationListener(new Animation.AnimationListener() {
				@Override
				public void onAnimationStart(Animation animation) {

				}

				@Override
				public void onAnimationRepeat(Animation animation) {
				}

				@Override
				public void onAnimationEnd(Animation animation) {
					Animation animRef = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.button_anim);  	
					nextStep.setAnimation(animRef);
					animRef.start();
				}
			});
			*/

		}	

	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if(isShowImageNeedAssert){
				getFragmentManager().beginTransaction().remove(assertFragment).commit();
				SharedPreferences preferences = this.getSharedPreferences(
						"assert_pref", Context.MODE_APPEND);
				Editor editor = preferences.edit();
				editor.putBoolean("isShowImageNeedAssert", false);
				editor.commit();
				isShowImageNeedAssert=false;
			}else{
				goToGallerySelectActivity();
			}
		}
		return false;
	}

}
